import router from './router';
import { useUserStore } from '@/stores/user';
import NProgress from 'nprogress';
import { login } from '@/utils/login';
import { ElMessage } from 'element-plus';


function getParam (variable) {
  var query = window.location.search.substring(1)
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=')
      if (pair[0] === variable) {
          return pair[1]
      }
  }
  return false
}

function nextFunction (to, from, next) {
  const redirect = decodeURIComponent(from.query.redirect || to.path)
  console.log(redirect)
  if (to.path === redirect) {
    // set the replace: true so the navigation will not leave a history record
    if (redirect === '/') {
      next({ path: '/' })
      NProgress.done()
    }
  } else {
    // 跳转到目的路由
    next({ path: redirect })
  }
  NProgress.done()
}

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  NProgress.start();
  const token = userStore.token;

  if (token) {
    console.log('token11111')
    next();
  } else {
    const code = getParam('code');
    if (code) {
      // userStore.$reset();
      // localStorage.clear();
      console.log('获取到 code:', code);
      login(code).then(res => {
        console.log('登录响应:', res);
        if (res.status === 200) {
          const { token, refresh_token, name, image, username } = res.result || {};
          if (!token) {
            console.error('未获取到 token,响应数据:', res);
            throw new Error('Token 无效');
          }
          userStore.setToken(token);
          userStore.setRefreshToken(refresh_token);
          userStore.setUserInfo({ name, image, username });
          localStorage.setItem('ACCESS_TOKEN', token);
          localStorage.setItem('REFRESH_TOKEN', refresh_token);
          nextFunction(to, from, next);
        } else {
          // ✅ 从 res.data 获取 message
          ElMessage.error(res.message || '登录失败，请重试');
        }
      }).catch(error => {
        // ✅ 捕获错误并提取 message
        const errorMessage = error.response?.data?.message || error.message || '登录失败，请重试';
        ElMessage.error(errorMessage);
      });
    } else {
      ElMessage.error('未获取到登录凭证，请重新登录');
    }
  }
});

